#!/usr/bin/env python
# -*- coding:utf-8 -*-


from jujud.jujud import Jujube, Server

from jujud import log

#######################################################################

class EchoServer(Server)  :
    '''Echo Consumer'''
    def serve(self, service, record, address_from) :
        if log.debugable :
            log.debug('SERVICE "%s" echo "%s" from "%s"', service, record, address_from)
        # echo back
        address_to = address_from
        return service, record, address_to
        # serve()
    # class EchoServer


#######################################################################

HOST = "127.0.0.1"
PORT = 54344

def main(options):
    if options.verbose :
        log.enableDebug()
    else :
        log.disableDebug()

    s = Jujube()
    s.listenTCP(PORT)

    server = EchoServer()
    s.registerService('ECHO', server)
    s.run()
    # main()

if __name__ == '__main__' :
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False,
                        help='show detail information')
    parser.add_option("", "--profile", dest="profile", action="store_true", default=False,
                        help='show profile information')
    (options, args) = parser.parse_args()
    if options.profile :
        prof_file = 'prof.echo.txt'
        import cProfile
        cProfile.run("main(options)", prof_file)
        import pstats
        p = pstats.Stats(prof_file)
        #p.sort_stats("time").print_stats()
        p.sort_stats("cumulative").print_stats()
    else :
        main(options)

    import sys
    sys.exit(0)

